# 项目参数
RELEASE_IMAGE_PREFIX=swr.cn-north-4.myhuaweicloud.com/chenhonghua
RELEASE_EXE=exercise_repository
PKGNAME?=gitee.com/chenhonghua/common-service
CGO_ENABLED?=1

# 当前路径
MK_DIR=$(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))
# 代码版本。用于细分安装包所在代码版本。
GIT_VERSION?=$(shell git rev-parse --short HEAD)
@echo "代码版本: $(GIT_VERSION)"
# 动态版本。用于重复构建区分镜像版本。
META_VERSION?=$(shell expr `date +"%y%m%d"` + 0).$(shell expr `date +"%H%M"` + 0)

# 容器镜像版本
IMAGE_TAG?=$(META_VERSION).$(GIT_VERSION)
# 容器镜像构建、管理引擎
BUILD_IMAGE_ENGINE?=docker

SEPARATOR_LINE=--------------------------------------------------------------------------------

# 默认操作
.DEFAULT_GOAL=compile

.PHONY: clean
clean:
	@echo "$(SEPARATOR_LINE)"
	@echo "操作: 清理编译文件"
	@-rm -rf $(MK_DIR)/$(RELEASE_EXE)
	@echo "$(SEPARATOR_LINE)"

compile: clean
	@echo "$(SEPARATOR_LINE)"
	@echo "操作: 编译"
	@go clean
	@go mod tidy
	@go mod vendor
	CGO_ENABLED=$(CGO_ENABLED) GOBIN=$(MK_DIR)/ go install -buildvcs=false -mod=vendor $(PKGNAME)/cmd/$(RELEASE_EXE)
	@echo "编译完成: $(MK_DIR)/$(RELEASE_EXE)"
	@echo "$(SEPARATOR_LINE)"

image-clean:
	@echo "$(SEPARATOR_LINE)"
	@echo "操作: 清理容器镜像"
	@-$(BUILD_IMAGE_ENGINE) images |grep $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE) |awk '{print $$1":"$$2}' |xargs $(BUILD_IMAGE_ENGINE) rmi
	@-$(BUILD_IMAGE_ENGINE) image prune -f
	@echo "$(SEPARATOR_LINE)"

image: compile image-clean
	@echo "$(SEPARATOR_LINE)"
	@echo "操作: 构建容器镜像"
	$(BUILD_IMAGE_ENGINE) build --no-cache --build-arg APP=$(RELEASE_EXE) -t $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE) $(MK_DIR)/
	@#echo "镜像构建完成: $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE)"
	@$(BUILD_IMAGE_ENGINE) tag $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE) $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE):$(IMAGE_TAG)
	@echo "镜像构建完成: $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE):$(IMAGE_TAG)"
	@echo "$(SEPARATOR_LINE)"

image-push: image
	@echo "$(SEPARATOR_LINE)"
	@echo "操作: 构建并推送容器镜像"
	@$(BUILD_IMAGE_ENGINE) push $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE)
	@#echo "镜像推送完成: $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE)"
	@$(BUILD_IMAGE_ENGINE) push $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE):$(IMAGE_TAG)
	@echo "镜像推送完成: $(RELEASE_IMAGE_PREFIX)/$(RELEASE_EXE):$(IMAGE_TAG)"
	@echo "$(SEPARATOR_LINE)"
